import { Button, Form, Input, Modal, Spin } from "antd";
import { useEffect, useState } from "react";
import { TypeSelect, UserSelect } from "../../components/IdSelect";
import { useTaskModal, useTasksQueryKey } from "./utils";
import { useForm } from "antd/lib/form/Form";
import { useDeleteTask, useEditTask } from "../../hooks/useTasks";
import { useQueryClient } from "react-query";
import { Task } from "../../types/task";

const formLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

export const TaskModal = () => {
  const {
    taskModalVisible,
    taskToBeEdited,
    closeTaskModal,
    isLoading: getLoading,
  } = useTaskModal();
  const queryKey = useTasksQueryKey();
  const { mutateAsync: editTask } = useEditTask(queryKey);
  const { mutateAsync: deleteTask } = useDeleteTask(queryKey);
  const [form] = useForm();
  const queryClient = useQueryClient();
  const [confirmLoading, setConfirmLoading] = useState(false);

  const close = () => {
    form.resetFields();
    closeTaskModal();
  };
  const onDelete = async () => {
    if (taskToBeEdited === undefined) return;
    Modal.confirm({
      title: "确认删除任务吗？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        close();
        return deleteTask(taskToBeEdited.id);
      },
    });
  };
  const hasFormChanged = () => {
    if (taskToBeEdited === undefined) return true;
    const taskDiff = form.getFieldsValue();
    type editKeys = keyof typeof taskDiff;
    for (let key in taskDiff) {
      if (taskToBeEdited[key as Extract<Task, editKeys>] !== taskDiff[key])
        return true;
    }
    return false;
  };
  const handleSubmit = async () => {
    if (!hasFormChanged() || taskToBeEdited === undefined) {
      close();
      return;
    }
    setConfirmLoading(true);
    await editTask({ ...taskToBeEdited, ...form.getFieldsValue() });
    await queryClient.invalidateQueries(["tasks", taskToBeEdited.id]);
    setConfirmLoading(false);
    close();
  };

  useEffect(() => {
    form.setFieldsValue(taskToBeEdited);
  }, [form, taskToBeEdited]);
  return (
    <Modal
      title="编辑任务"
      visible={taskModalVisible}
      okText="确认"
      cancelText="取消"
      onOk={handleSubmit}
      onCancel={close}
      confirmLoading={confirmLoading}
      forceRender={true}
    >
      <Spin spinning={getLoading}>
        <Form {...formLayout} form={form}>
          <Form.Item
            name="name"
            label="任务名"
            rules={[{ required: true, message: "请输入任务名" }]}
          >
            <Input type="text" />
          </Form.Item>
          <Form.Item name="processorId" label="经办人">
            <UserSelect />
          </Form.Item>
          <Form.Item name="typeId" label="类型">
            <TypeSelect />
          </Form.Item>
        </Form>
        <div style={{ textAlign: "right" }}>
          <Button
            danger={true}
            onClick={onDelete}
            size="small"
            style={{ fontSize: "14px" }}
          >
            删除
          </Button>
        </div>
      </Spin>
    </Modal>
  );
};
